package com.zhongyi.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.util.StringUtils;

/**
 * 自定义字符串处理类
 * <p>
 * 
 *
 * @author <a href="mailto:lysongfei@gmail.com">songfei</a>
 * @version 3.0, 2012-4-24
 */
public class StringUtil {
	
	private static final int CHAR_BUFFER_SIZE = 200; 
	
	public static String readHtmlToString(String htmlPath){
		InputStreamReader isReader = null;
		StringBuilder sBuilder = new StringBuilder();
		if(htmlPath != null && htmlPath.length() > 0){
			int index = -1;
			File file = new File(htmlPath);
			char[] cs = new char[CHAR_BUFFER_SIZE];
			if(file.exists()){//文件存在
				try {
					isReader = new InputStreamReader(new FileInputStream(file));
					index = isReader.read(cs);
					while(index != -1){
						sBuilder.append(cs, 0, index);
						index = isReader.read(cs);
					}
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}finally{
					if(isReader != null){
						try {
							isReader.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
		return sBuilder.toString();
	}
	
	public static String readHtmlToString(InputStream ins){
		InputStreamReader isReader = null;
		StringBuilder sBuilder = new StringBuilder();
		int index = -1;
		char[] cs = new char[CHAR_BUFFER_SIZE];
		try {
			isReader = new InputStreamReader(ins);
			index = isReader.read(cs);
			while(index != -1){
				sBuilder.append(cs, 0, index);
				index = isReader.read(cs);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(isReader != null){
				try {
					isReader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return sBuilder.toString();
	}
	
	public static String parseHtmlString(String htmlString){
		return null;
	}
	
	/**
	 * 字符串清洗
	 * @param str
	 * @return
	 */
	public static String parseString(String str){
		String result = null;
		if(str != null && str.length() > 0){
			Pattern pattern = Pattern.compile("\\s*|\t|\r|\n");
			//去除字符串中空格、回车、换行符
			Matcher matcher = pattern.matcher(str);
			result = matcher.replaceAll("");
			
		}
		return result;
	}
	
	/**
	 * 验证邮件格式是否正确
	 * @param email
	 * @return
	 */
    public static boolean isEmailAddress(String email) {   
        Pattern emailer = Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");   
         if (!StringUtils.hasText(email))   
             return false;   
         email = email.toLowerCase();   
         return emailer.matcher(email).matches();   
     }   

}
